﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.With.Apliaction.Command.InventoryCommand;
using DAL;
using MediatR;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.With.Apliaction.CommandHandler.StoreCommand
{
    /// <summary>
    /// 新增加入库命令处理程序
    /// </summary>
    public class StoreAddCommandHandler : IRequestHandler<StoreAddCommand, ApiReqult<object>>
    {
        private readonly DBHelper _dbHelper;
        private const int BatchSize = 100; // 每批处理的数据数量

        public StoreAddCommandHandler(DBHelper dbHelper)
        {
            _dbHelper = dbHelper;
        }

        public async Task<ApiReqult<object>> Handle(StoreAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<object>();

            try
            {
                int totalRows = 0;
                if (request.Pid != null && request.Pid.Count > 0)
                {
                    totalRows = await InsertRecordsInBatchesAsync(request);
                }

                result.Code = totalRows > 0 ? ApiEnum.添加成功 : ApiEnum.添加失败;
                result.Msg = result.Code == ApiEnum.添加成功 ? "入库数据添加成功" : "入库数据添加失败";
            }
            catch (SqlException ex)
            {
                result.Code = ApiEnum.添加失败;
                result.Msg = $"数据库操作失败：{ex.Message}";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.操作失败;
                result.Msg = $"系统异常：{ex.Message}";
            }

            return result;
        }

        private async Task<int> InsertRecordsInBatchesAsync(StoreAddCommand request)
        {
            int totalRowsInserted = 0;
            int totalCount = request.Pid.Count;

            for (int startIndex = 0; startIndex < totalCount; startIndex += BatchSize)
            {
                int endIndex = Math.Min(startIndex + BatchSize, totalCount);

                // 拆分成单独的行，方便设置断点
                Task<int> insertBatchTask = InsertBatchAsync(request, startIndex, endIndex);
                int rowsInserted = await insertBatchTask;

                totalRowsInserted += rowsInserted;
            }

            return totalRowsInserted;
        }

        private async Task<int> InsertBatchAsync(StoreAddCommand request, int startIndex, int endIndex)
        {
            StringBuilder sqlBuilder = new StringBuilder();

            // 构建 SQL 插入语句的开头部分
            string insertStatementStart = @"
            INSERT INTO ManagementModels (
                Pid, InboundNum, AssociatedNum, batch, Specifications,
                Quantity, Price, Binlocation, Storage, Supplier, SupplierID,
                SupplierName, SupplierPeople, SupplierPhone, Creator, Reviewer,
                OutAuditTime, OutAuditstatus, OutCreationTime, Rember, IsDelete,
                ProName, ProId, Unitprice, UNumber
            ) VALUES ";
            sqlBuilder.AppendLine(insertStatementStart);

            for (int i = startIndex; i < endIndex; i++)
            {
                int relativeIndex = i - startIndex;

                // 处理多个值的插入
                if (relativeIndex > 0)
                {
                    string comma = ",";
                    sqlBuilder.Append(comma);
                }

                // 构建每一行的插入值
                string pidValue = SanitizeValue(request.Pid[i]);
                string inboundNumValue = SanitizeValue(request.InboundNum[i]);
                string associatedNumValue = SanitizeValue(request.AssociatedNum[i]);
                string batchValue = SanitizeValue(request.batch[i]);
                string specificationsValue = SanitizeValue(request.Specifications[i]);
                string quantityValue = SanitizeValue(request.Quantity[i]);
                string priceValue = SanitizeValue(request.Price[i]);
                string binlocationValue = SanitizeValue(request.Binlocation[i]);
                string storageValue = SanitizeValue((int)request.Storage[i]);
                string supplierValue = SanitizeValue(request.Supplier[i]);
                string supplierIDValue = SanitizeValue(request.SupplierID[i]);
                string supplierNameValue = SanitizeValue(request.SupplierName[i]);
                string supplierPeopleValue = SanitizeValue(request.SupplierPeople[i]);
                string supplierPhoneValue = SanitizeValue(request.SupplierPhone[i]);
                string creatorValue = SanitizeValue(request.Creator[i]);
                string reviewerValue = SanitizeValue(request.Reviewer[i]);
                string outAuditTimeValue = SanitizeValue(request.OutAuditTime[i]);
                string outAuditstatusValue = SanitizeValue((int)request.OutAuditstatus[i]);
                string outCreationTimeValue = SanitizeValue(request.OutCreationTime[i]);
                string remberValue = SanitizeValue(request.Rember[i]);
                string isDeleteValue = SanitizeValue(request.IsDelete[i]);
                string proNameValue = SanitizeValue(request.ProName[i]);
                string proIdValue = SanitizeValue(request.ProId[i]);
                string unitpriceValue = SanitizeValue(request.Unitprice[i]);
                string uNumberValue = SanitizeValue(request.UNumber[i]);

                string rowInsertValue = $@"
                ({pidValue}, {inboundNumValue}, '{associatedNumValue}', '{batchValue}', '{specificationsValue}',
                '{quantityValue}', '{priceValue}', '{binlocationValue}', {storageValue}, '{supplierValue}', '{supplierIDValue}',
                '{supplierNameValue}', '{supplierPeopleValue}', '{supplierPhoneValue}', '{creatorValue}', '{reviewerValue}',
                '{outAuditTimeValue}', {outAuditstatusValue}, '{outCreationTimeValue}', '{remberValue}', {isDeleteValue},
                '{proNameValue}', '{proIdValue}', '{unitpriceValue}', '{uNumberValue}')";

                sqlBuilder.AppendLine(rowInsertValue);
            }

            string sql = sqlBuilder.ToString();

            // 执行非查询操作
            int rowsAffected = _dbHelper.NonQuery(sql);
            return rowsAffected;
        }

        private string SanitizeValue(object value)
        {
            if (value == null)
            {
                return "NULL";
            }
            string strValue = value.ToString();
            // 简单的转义单引号，防止 SQL 注入
            string sanitizedValue = strValue.Replace("'", "''");
            return sanitizedValue;
        }
    }
}